<template>
  <div class="materialAdd" v-loading="detailInfoShow">
    <!-- 筛选按钮 -->
    <div class="search-button" v-if="!contactAddShow">
      <el-button
        v-if="pageType !== 'detail'"
        class="btn save"
        @click="handleAddSave(materialFormRef)"
        ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
        >保存</el-button
      >
      <el-button class="btn direction" @click="handleBack"
        ><el-icon class="icon" color="#fff"> <Back /> </el-icon
        >返回</el-button
      >
    </div>
    <el-collapse v-model="activeNames">
      <!-- 基础信息 -->
      <el-collapse-item
        name="1"
        v-if="!contactAddShow"
        :class="contactAddShow ? 'customInfoUpClass' : 'customInfoDownClass'"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title"
            >{{
              pageType === "detail" ? "" : pageType === "add" ? "新增" : "编辑"
            }}用户信息</span
          >
        </template>
        <div class="material-info">
          <el-form
            :model="materialForm"
            ref="materialFormRef"
            :rules="queryRules"
            label-width="100"
            v-enterToNext
            :disabled="pageType === 'detail'"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="用户姓名" prop="nickName">
                  <el-input
                    ref="refInput"
                    class="search-input"
                    v-model="materialForm.nickName"
                    placeholder="请输入用户姓名"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="归属部门" prop="deptId">
                  <el-tree-select
                   class="search-input"
                   style="height:100%;"
                    v-model="materialForm.deptId"
                    :data="deptOptions"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children',
                    }"
                    value-key="id"
                    placeholder="请选择归属部门"
                    default-expand-all
                    check-strictly
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="手机号码" prop="phonenumber">
                  <el-input
                    class="search-input"
                    v-model="materialForm.phonenumber"
                    placeholder="请输入手机号码"
                    maxlength="11"
                  />
                </el-form-item>
              </el-col>
              <!-- v-if="materialForm.userId == undefined" -->
              <el-col :span="6">
                <el-form-item label="用户账号" prop="userName">
                  <el-input
                    class="search-input"
                    v-model="materialForm.userName"
                    placeholder="请输入用户账号"
                    maxlength="30"
                  />
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                  <el-form-item label="邮箱" prop="email">
                     <el-input v-model="materialForm.email" placeholder="请输入邮箱" maxlength="50" />
                  </el-form-item>
               </el-col> -->
              <!-- </el-row>
            <el-row> -->
              <!-- <el-col :span="6" v-if="materialForm.userId == undefined">
                <el-form-item label="用户密码" prop="password">
                  <el-input
                    class="search-input"
                    v-model="materialForm.password"
                    placeholder="请输入用户密码"
                    type="password"
                    maxlength="20"
                    show-password
                  />
                </el-form-item>
              </el-col> -->

              <el-col :span="6">
                <el-form-item label="用户性别">
                  <el-select
                    class="search-input"
                    v-model="materialForm.sex"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="dict in sys_user_sex"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="角色">
                  <el-select
                    style="width: 268px"
                    v-model="materialForm.roleIds"
                    multiple
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in roleOptions"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleId"
                      :disabled="item.status == 1"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="false">
                <el-form-item label="上层流程角色">
                  <el-select
                    style="width: 268px" clearable
                    v-model="materialForm.supRoleid"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in roleOptions"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleId"
                      :disabled="item.status == 1 || item.flowFlag==null || item.flowFlag==0"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="岗位">
                  <el-select
                    style="width: 268px"
                    v-model="materialForm.postIds"
                    multiple
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in postOptions"
                      :key="item.postId"
                      :label="item.postName"
                      :value="item.postId"
                      :disabled="item.status == 1"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态">
                  <el-radio-group v-model="materialForm.status">
                    <el-radio
                      v-for="dict in sys_normal_disable"
                      :key="dict.value"
                      :label="dict.value"
                      >{{ dict.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
       
              <el-col :span="12">
                <el-form-item label="备注">
                  <el-input
                    style="width: 96%"
                    v-model="materialForm.remark"
                    type="textarea"
                    maxlength="2000"
                    placeholder="请输入内容"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);
import { getDictsApi } from "@/api/dict";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
} from "@/api/system/user";
import { ElMessage, ElMessageBox } from "element-plus";
import { getMaterialClassListApi } from "@/api/information/materialClass";
import { getSupplierListApi } from "@/api/information/supplier";
import {
  addMaterialApi,
  getMaterialApi,
  editMaterialApi,
} from "@/api/information/material";
const emit = defineEmits([
  "materialAddShow",
  "update:materialAddShow",
  "updateEvaluateAddShow",
  "refreshList",
]);
const props = defineProps({
  pageType: {
    type: String,
    default: "add",
  },
});
const activeNames = ref(["1", "2", "3"]);
const materialFormRef = ref();
const detailInfoShow = ref(false);
const refInput = ref();
const unitList = ref([]);
const stockTypeList = ref([]);
const suppliereList = ref([]);
const taxRateList = ref([]);
const postOptions = ref([]);
const roleOptions = ref([]);
const deptOptions = ref(undefined);

const materialFormTemplate = {
  userId: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  password: "111111",
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: "0",
  remark: undefined,
  postIds: [],
  roleIds: [],
  supRoleid:null
};
const data = reactive({
  materialForm: JSON.parse(JSON.stringify(materialFormTemplate)),
  queryRules: {
    userName: [
      { required: true, message: "用户账号不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户账号长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户姓名不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
  contactTypeList: [],
  templateList: [
    {
      label: "是",
      value: 1,
    },
    {
      label: "否",
      value: 0,
    },
  ],
  classOptions: [],
});
const { materialForm, queryRules, templateList, classOptions } = toRefs(data);
const contactAddShow = ref(false);

// 保存
const handleAddSave = async (materialFormRef) => {
  if (!materialFormRef) return;
  await materialFormRef.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          if (materialForm.value.userId != undefined) {
            updateUser(materialForm.value).then((res) => {
              emit("update:materialAddShow", false);
              emit("refreshList", true);
              ElMessage.success(res.msg);
              materialForm.value = JSON.parse(
                JSON.stringify(materialFormTemplate)
              );
            });
          } else {
            addUser(materialForm.value).then((res) => {
              emit("update:materialAddShow", false);
              emit("refreshList", true);
              ElMessage.success(res.msg);
              materialForm.value = JSON.parse(
                JSON.stringify(materialFormTemplate)
              );
            });
          }
        })
        .catch(() => {});
    } else {
      console.log("error submit!");
    }
  });
};

/** 获取分类列表  */
const getMaterialClassList = async () => {
  const res = await getMaterialClassListApi();
  res.rows.forEach((item) => {
    item.id = item.categoryId;
  });
  classOptions.value = proxy.handleTree(res.rows, "id");
};

const handleBack = () => {
  if (props.pageType === "detail") {
    emit("updateEvaluateAddShow", false);
    emit("update:materialAddShow", false);
    materialForm.value = JSON.parse(JSON.stringify(materialFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("updateEvaluateAddShow", false);
        emit("update:materialAddShow", false);
        materialForm.value = JSON.parse(JSON.stringify(materialFormTemplate));
      })
      .catch(() => {});
  }
};

// 字典
async function getDicts() {
  getUser().then((response) => {
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
  });
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}

// 处理详情信息
const handleDetailInfo = async (userId) => {
  try {
    detailInfoShow.value = true;
    getUser(userId).then((response) => {
      materialForm.value = response.data;
      postOptions.value = response.posts;
      roleOptions.value = response.roles;
      materialForm.value.postIds = response.postIds;
      materialForm.value.roleIds = response.roleIds;
      materialForm.value.supRoleid = response.data.supRoleid;
      detailInfoShow.value = false;
    });
  } catch (error) {
    detailInfoShow.value = false;
  }
};

onMounted(() => {
  getDicts();
  getMaterialClassList();
  nextTick(() => {
    refInput.value.focus(); // 聚焦
  });
});

defineExpose({
  handleDetailInfo,
});
</script>
<style>
.autocomplete-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  background-color: #f8faff;
}

.materialAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;

  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  /* .search-button {
    position: fixed;
    top: 110px;
    right: 60px;
    display: flex;
    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90px;
      height: 34px;
      padding: 10px;
      // margin-right: 20px;
      font-size: 14px;
      border-radius: 4px;
      user-select: none;
      cursor: pointer;
    }
    .btn.save {
      color: #fff;
      background: rgba(67, 207, 124, 1);
      border: none;
      &:hover {
        background: rgba(67, 207, 124, 0.85);
      }
    }

    .btn.add {
      .btn.add {
        border: none;
        color: #fff;
        background: rgba(255, 159, 0, 1);
        &:hover {
          background: rgba(255, 159, 0, 0.85);
        }
      }
    }

    .btn.back {
      border: none;
      color: #fff;
      background: rgba(255, 159, 0, 1);
      &:hover {
        background: rgba(255, 159, 0, 0.85);
      }
    }
    .btn.direction {
      border: none;
      color: #fff;
      background: rgba(153, 153, 153, 1);
      &:hover {
        background: rgba(153, 153, 153, 0.85);
      }
    }

    .icon {
      margin-right: 6px;
    }
  } */
  .circle {
    margin: 0 10px 0 20px;
    width: 6px;
    height: 6px;
    background: #007cef;
    border-radius: 50%;
  }
  .collapse-title {
    font-weight: bold;
    font-size: 16px;
  }
  .el-collapse,
  .el-collapse-item__wrap {
    border: none;
  }

  .search-input {
    width: 268px;
    height: 34px;
  }
  .material-info {
    padding: 20px 10px 5px 10px;
    background-color: #fafafa;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
    .table-operate {
      display: flex;
      justify-content: space-around;
      .table-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
    }
  }
  .button-position {
    top: 6px;
    right: 30px;
  }
  :deep(.el-input__inner) {
    height: 34px;
  }
  .customInfoUpClass {
    -webkit-animation: customInfoDown 0.8s ease-out;
  }
  .customInfoDownClass {
    -webkit-animation: customInfoDown 0.8s ease-out;
  }

  .contactInfoUpClass {
    -webkit-animation: contactInfoUp 0.8s ease-out;
  }
  .contactInfoDownClass {
    -webkit-animation: contactInfoUp 0.8s ease-out;
  }
  @-webkit-keyframes customInfoUp {
    0% {
      opacity: 0;
      -webkit-transform: translateY(80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  @-webkit-keyframes customInfoDown {
    0% {
      opacity: 0;
      -webkit-transform: translateY(-80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
  @-webkit-keyframes contactInfoUp {
    0% {
      opacity: 0;
      -webkit-transform: translateY(80px);
    }

    100% {
      opacity: 1;
      -webkit-transform: translateY(0px);
    }
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: center;
  // white-space: nowrap; /* 禁止换行 */
  // overflow: hidden; /* 隐藏超出部分 */
  // text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
</style>
